 <!-- 整理一下构思：
一个简单的表格页面，该每一行一个按钮功能跳转到详细页面，并带上数据编号，拿着数据编号去后端拿历史数据，通过这折线图什么的来显示出来
-->

<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="6">
        <span style="margin-left:5px;">采集类型：</span>
        <el-select v-model="typeId" placeholder="请选择" @change="getList()">
          <el-option
            v-for="item in typeNames"
            :key="item.typeId"
            :value="item.typeId"
            :label="item.typeName"
          />
        </el-select>
      </el-col>
      <el-button type="primary" style="float: right; margin-right: 8%;" @click="handleOpenDialog">修改阈值</el-button>
    </el-row>

    <el-dialog title="修改阈值" :center="true" :visible.sync="outVisible" :before-close="outClose">
      <div style="display: flex; justify-content: center;">
        <el-form label-width="120px">
          <el-form-item v-for="item in temwarn" :key="item.typeId" :label="gettypename(item)">
            <span style="text-align: center;margin: 0 10px 0 20px;">警告阈值</span>
            <el-input-number v-model="item.warn1" :controls="false" />
            <span style="text-align: center;margin: 0 10px;">危险阈值</span>
            <el-input-number v-model="item.warn2" :controls="false" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="editwarn">确认</el-button>
      </span>
    </el-dialog>

    <el-table
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ textAlign: 'center' }"
      :default-sort="{ prop: 'typeId', order: 'null' }"
      fit
      @row-click="GoToDetails"
    >
      <el-table-column label="编号" width="120" align="center">
        <template slot-scope="{ $index }">
          {{ getCustomIndex($index) }}
        </template>
      </el-table-column>

      <el-table-column prop="typeName" label="地点" align="center" />

      <el-table-column prop="type" label="设备类型" align="center" :formatter="gettypename" />

      <el-table-column prop="typedata" :label="updateLabel" align="center" :formatter="formatTypedata" />

      <el-table-column prop="updatedate" label="上次更新时间" align="center" />

      <el-table-column label="状态" width="380" align="center">
        <template slot-scope="scope">
          <p :class="getStatusClass(scope.row)" />
        </template>
      </el-table-column>

    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
      tableData: [// 范例数据，设备名称，可用状态，采集值
      ],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10
      },
      dynamicLabel: '全部数据', // 初始标签文本
      typeNames: [
        { typeId: 'all', typeName: '全部数据' },
        { typeId: 'temperature', typeName: '温度检测', unit: '°C' },
        { typeId: 'humidity', typeName: '湿度检测', unit: '%' },
        { typeId: 'noiseLevel', typeName: '噪音水平', unit: 'dB' },
        { typeId: 'airPressure', typeName: '气压', unit: 'hPa' },
        { typeId: 'windSpeed', typeName: '风速', unit: 'm/s' },
        { typeId: 'airQualityIndex', typeName: '空气质量指数', unit: 'AQI' }
      ],
      warn: [
        { typeId: 'temperature', warn1: 10, warn2: 15 },
        { typeId: 'humidity', warn1: 10, warn2: 15 },
        { typeId: 'noiseLevel', warn1: 10, warn2: 15 },
        { typeId: 'airPressure', warn1: 10, warn2: 15 },
        { typeId: 'windSpeed', warn1: 10, warn2: 15 },
        { typeId: 'airQualityIndex', warn1: 10, warn2: 15 }
      ],
      typeId: 'all',
      showDetails: 1,
      isshow: 0,
      outVisible: false,
      innerVisible: false,
      formData: { date: '', name: '', address: '' },
      temwarn: [
        { typeId: 'temperature', warn1: 10, warn2: 15 },
        { typeId: 'humidity', warn1: 10, warn2: 15 },
        { typeId: 'noiseLevel', warn1: 10, warn2: 15 },
        { typeId: 'airPressure', warn1: 10, warn2: 15 },
        { typeId: 'windSpeed', warn1: 10, warn2: 15 },
        { typeId: 'airQualityIndex', warn1: 10, warn2: 15 }
      ]
    }
  },
  computed: {
    getCustomIndex() {
      return function(index) {
        return index + 1 + (this.listQuery.page - 1) * this.listQuery.limit
      }
    },
    updateLabel() {
      const typeIdOneValues = this.typeNames
        .filter(item => item.typeId === this.typeId) // 过滤出 typeId 为 1 的对象
      console.log(typeIdOneValues[0].typeName)
      return typeIdOneValues[0].typeName
    },
    getWarn() {
      return typeId => {
        const item = this.warn.find(w => w.typeId === typeId)
        return item ? item.warn1 : 0
      }
    }
  },
  created() {
    this.getList()
    this.getthresholds()
  },
  mounted() {
  },
  methods: {
    GoToDetails(row) {
      console.log(row)
      var id = row.Id
      var typeName = row.typeId
      var from = row.typeName
      this.$router.push({ path: 'environment-Details', query: { id: id, typeName: typeName, from: from }})
    },
    getList() {
      this.axios({
        method: 'get',
        url: 'http://139.9.77.245:8081/environment-data/' + this.listQuery.page + '/' + this.listQuery.limit + '/' + this.typeId
      }).then(response => { // 使用箭头函数
        const ret = response.data
        if (ret.code === 0) {
          console.log(ret)
          this.total = ret.data.total
          const Data = ret.data.records.map(item => ({
            Id: item.deviceId,
            typeId: item.type,
            typeName: item.deviceLocation,
            updatedate: item.deviceTime,
            typedata: item.doserate
          }))
          this.tableData = Data
          // console.log(this.tableData)
        } else {
          console.log('信息获取失败')
          console.log(ret)
        }
      }).catch(error => {
        console.error('请求出错:', error)
      })
    },
    getthresholds() {
      // 获取阈值
      for (let i = 0; i < this.warn.length; i++) {
        console.log(this.warn[i].typeId)
        this.axios({
          method: 'get',
          url: 'http://139.9.77.245:8081/thresholds/' + this.warn[i].typeId
        }).then(response => { // 使用箭头函数
          const ret = response.data
          if (ret.code === 0) {
            console.log(ret)
            this.warn[i].id = ret.data.id
            this.warn[i].warn2 = ret.data.dangerThreshold
            this.warn[i].warn1 = ret.data.warningThreshold
            this.temwarn[i].id = JSON.parse(JSON.stringify(this.warn[i].id))
            this.temwarn[i].warn2 = JSON.parse(JSON.stringify(this.warn[i].warn2))
            this.temwarn[i].warn1 = JSON.parse(JSON.stringify(this.warn[i].warn1))
          // console.log(this.tableData)
          } else {
            console.log('信息获取失败')
            console.log(ret)
          }
        }).catch(error => {
          console.error('请求出错:', error)
        })
      }
    },
    toUpdateUser(typeId) {
      this.$router.push('/machine_type/machine_type-update/' + typeId)
    },
    saveState() {
      // 模块化后，调用 state 的代码修改为 this.$store.state.myuser
      sessionStorage.setItem('userState', JSON.stringify(this.$store.state.myuser))
    },
    showMark(row, event, column) {
      console.log('测试点击')
      this.$emit('handleFather', row)
    },
    formatTypedata(row) {
      const typeIdOneValues = this.typeNames
        .filter(item => item.typeId === row.typeId) // 过滤出 typeId 为 1 的对象
      // console.log(typeIdOneValues[0].unit)
      return row.typedata + typeIdOneValues[0].unit // 添加 m 单位 for typeId 为 2 的数据
    },
    gettypename(row) {
      const typeIdOneValues = this.typeNames
        .filter(item => item.typeId === row.typeId) // 过滤出 typeId 为 1 的对象
      // console.log(typeIdOneValues[0].typeName)
      return typeIdOneValues[0].typeName
    },
    getStatusClass(row) {
    // 根据警戒值判断状态，并返回相应的类名
      // console.log(this.warn)
      // console.log(row.typeId)
      const typeIdOneValues = this.warn
        .filter(item => item.typeId === row.typeId) // 过滤出 typeId 为 1 的对象

      // console.log(typeIdOneValues[0]) // 输出 typeId 的对象的 value 值数组
      if (row.typedata > typeIdOneValues[0].warn2) {
        return 'red-box'
      } else if (row.typedata > typeIdOneValues[0].warn1) {
        return 'yellow-box'
      } else { return 'blue-box' }
    },
    handleOpenDialog() {
      this.outVisible = true
    },
    outClose(done) {
      console.log(this.warn)
      console.log(this.temwarn)
      this.temwarn = JSON.parse(JSON.stringify(this.warn))
      done()
    },
    handleEdit(row) {
      this.formData = row
      this.innerVisible = true
    },
    editwarn() {
      // 修改警戒值
      // 创建要发送的数据对象
      for (let i = 0; i < this.temwarn.length; i++) {
        const requestData = {
          id: this.temwarn[i].id,
          name: this.temwarn[i].typeName,
          type: this.temwarn[i].typeId,
          warningThreshold: this.temwarn[i].warn1,
          dangerThreshold: this.temwarn[i].warn2
        }
        // 发起 POST 请求并传递参数
        this.axios({
          method: 'put',
          url: 'http://139.9.77.245:8081/thresholds/',
          data: requestData
        }).then(response => {
          const ret = response.data
          if (ret.code === 0) {
          // 处理成功响应
          } else {
            console.log('信息获取失败')
            console.log(ret)
          }
        }).catch(error => {
          console.error('请求出错:', error)
        })
      }
      this.$message({
        message: '修改成功',
        type: 'success'
      })
      this.warn = this.temwarn
    }
  }
}
</script>

<style scoped>
.red-text {
  color: red;
}
:deep .red-row {
  background-color: red;
  color: rgb(0, 0, 0);
}
:deep .yellow-row {
  background-color: yellow;
  color: rgb(0, 0, 0);
}
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
}
.red-box {
  float: right;
  margin-right: 140px;
  width: 80px;
  height: 18px;
  background-color: red;
}
.yellow-box {
  float: right;
  margin-right: 140px;
  width: 80px;
  height: 18px;
  background-color: yellow;
}
.blue-box {
  float: right;
  margin-right: 140px;
  width: 80px;
  height: 18px;
  background-color: blue;
}
</style>
